import { showToast } from "./uniApp";
import type { requestParams } from '@/types/global';

export const request = <T>(options: requestParams):Promise<T> => {
  const Token = uni.getStorageSync('token') || '';
  const defaultHeader = {
    'token': ''
  };
  const { url, method, data={} } = options;
  if (Token) {
    defaultHeader.token = `${Token}`
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: import.meta.env.VITE_APP_BASE_URL + url,
      header: {
        ...defaultHeader,
        'Content-Type': 'application/json'
      },
      method,
      data
    }).then(res => {
      const { code, msg, data }:any = res.data;
      if (code === 200) {
        resolve(data);
      } else if (code === 401) {
        uni.clearStorageSync();
      } else {
        showToast(msg);
        reject(data)
      }
    }).catch(err => {
      reject(err)
    })
  })
}